package engine.systems.update.threshold
{
	import engine.classes.enumerations.Comparator;
	import engine.classes.enumerations.SystemPriority;
	import engine.groups.Group;
	import engine.systems.update.GameSystem;
	import engine.utils.MathUtils;

	public class ThresholdSystem extends GameSystem
	{
		private var data:ThresholdData;
		private var component:Class;
		private var value:Number;
		
		public function ThresholdSystem()
		{
			super(ThresholdNode, updateNode);
			
			this.priority = SystemPriority.UPDATE;
		}
		
		public function updateNode(node:ThresholdNode, time:Number):void
		{
			for each(data in node.threshold.data)
			{
				component = node.entity.get(data.component);
				if(!component) continue;
				
				if(!component.hasOwnProperty(data.property) continue;
				value = component[data.property];
				
				switch(data.comparator)
				{
					case Comparator.EQUAL:
						this.trigger(value == data.value);
						break;
					
					case Comparator.GREATER:
						this.trigger(value > data.value);
						break;
					
					case Comparator.GREATER_OR_EQUAL:
						this.trigger(value >= data.value);
						break;
					
					case Comparator.LESSER:
						this.trigger(value < data.value);
						break;
					
					case Comparator.LESSER_OR_EQUAL:
						this.trigger(value <= data.value);
						break;
				}
			}
		}
		
		private function trigger(inside:Boolean):void
		{
			if(inside)
			{
				if(data.inside) return;
				data.inside = true;
				
				if(data.entered.numListeners > 0)
					data.entered.dispatch();
			}
			else
			{
				if(!data.inside) return;
				data.inside = false;
				
				if(data.exited.numListeners > 0)
					data.exited.dispatch();
			}
		}
	}
}